<?php
// 获取器 （抓取 HTML 保存）
namespace App\Handlers;

use GuzzleHttp\Client;
use Overtrue\Pinyin\Pinyin;
use Illuminate\Support\Facades\Storage;

class DownHtmlHandler
{
	public function get($url)
	{
		$http = new Client;

		$response = $http->get($url);

		if ($response->getStatusCode() === 200) {
			return $result = $response->getBody()->getContents();
		}
        return false;
	}
	public function getByMobile ($url) 
	{
		$http = new Client(['headers' => [
			'User-Agent' => 'Mozilla/5.0 (Linux; Android 7.0; STF-AL10 Build/HUAWEISTF-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043508 Safari/537.36 V1_AND_SQ_7.2.0_730_YYB_D QQ/7.2.0.3270 NetType/4G WebP/0.3.0 Pixel/1080',
		]]);
		$response = $http->get($url);
		if ($response->getStatusCode() === 200) {
			return $result = $response->getBody()->getContents();
		}
        return false;
	}
	public function getIndex($name) 
	{
		// $url = 'https://tieba.baidu.com/m?kw=' . urlencode($name);
		$url = 'https://tieba.baidu.com/f?ie=utf-8&kw=' . urlencode($name);
		if ($content = $this->get($url)) {
			$filename = $this->pinyin($name) . date('/Y/md/') . 'index/' . time() . '.html';
			Storage::disk('tieba')->put($filename, $content);
			return $filename;
		}
		return false;
	}
	public function getSubject($path)
	{
		$url = 'https://tieba.baidu.com/mo/q---43A2D763628BF4BFB6C9CBE68B0F4B88:FG=1-,-2-3-0--2/m?kz=' . $path;
		if ($content = $this->getByMobile($url)) {
			$filename = date('/Y/md/') . 'subject/' . $path . '.html';
			Storage::disk('tieba')->put($filename, $content);
			return $filename;
		}
		return false;
	}
	public function pinyin($text)
    {
        return str_replace('-', '', app(Pinyin::class)->permalink($text));
    }
}